//
//  PhotoBrowserViewController.swift
//  SinaWeiBoProject
//
//  Created by 房城鸿 on 15/10/21.
//  Copyright © 2015年 房兰峰. All rights reserved.
//

import UIKit

import SVProgressHUD

private let HMPhotoBrowserCellID = "HMPhotoBrowserCellID"

class PhotoBrowserViewController: UIViewController {

    //MARK: - 控制器属性
    ///  照片URL数组
    var urls:[NSURL]
    /// 用户选中的图片索引
    var selectedIndexPath:NSIndexPath
    
    //MARK: - 保存图像
    @objc private func saveImage(){
        //1.获取图像
        // 先拿到索引
        let path = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(path) as! PhotoBrowerCell
        
        //提示： 不一定能够下载到图像
        guard let image = cell.imageView.image else{
            SVProgressHUD.showInfoWithStatus("没有图像")
            return
        }
        //2.保存图像
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    @objc private func image(image:UIImage ,didFinishSavingWithError error: NSError ,contextInfo:AnyObject){
        print("OK")
    }
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    
    
    //MARK: -   构造函数的好处
    //1. 简化外部的调用
    //2. 可以不使用可选项属性，避免后续的解包问题
    init(urls:[NSURL],indexPath:NSIndexPath){
    
        self.urls = urls
        selectedIndexPath = indexPath
        
        //TODO: - 这里一定要重写这个父类的方法
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 加载界面
    override func loadView() {
        
        //创建全屏的视图（结构体修改属性要用 var ，对象不需要）
        
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        
        view = UIView(frame: rect)
        view.backgroundColor = UIColor.blackColor()
        
        //设置界面
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        printLog(urls)
        printLog(selectedIndexPath)
    }
    
    

    // 视图完成布局，准备开始显示
    // 开发提示，具体选择哪一个视图声明周期函数，一定要打断点，调试，不要死记硬背
    // 不同的控制器，collectionVC, tableVC, viewVC 声明周期函数执行的频率不一样，会根据子控件的类型以及个数会受到音效概念股
    // collectionVC 的 viewDidLayoutSubviews 之前的版本调用频率高！
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //collectionView 滚到懂用户选择的图片
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        
        //分页控件的当前显示页码
        pageControl.currentPage = selectedIndexPath.item
    }
    
    
    //视图出现
//    override func viewDidAppear(animated: Bool) {
//        super.viewDidAppear(animated)
//        //collectionView 滚到懂用户选择的图片
//        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
//    }
    
    //MARK: - 设置界面
    private func setupUI(){
        //1.添加控件
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        view.addSubview(pageControl)
        
        //2. 布局
        collectionView.frame = view.bounds
        
        //MARK: - 使用自带的布局
        let viewDict = ["saveButton":saveButton,"closeButton":closeButton]
        
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        
        /**
        自动布局的约束逻辑关系
        
        == 可以省略
        >= 
        <=
        */
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[saveButton(80)]-(>=80)-[closeButton(80)]-28-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[closeButton(35)]-8-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[saveButton(35)]-8-|", options: [], metrics: nil, views: viewDict))
        
        //pageControl 分页的布局
        view.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: -10))
        
        view.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -8))
        //布局 collectionView
        prepareCollectionView()
        
        //设置 
        preparePageControl()
        
        //关闭按钮的监听方法
        closeButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext { [weak self] (btn) -> Void in
            self?.dismissViewControllerAnimated(true, completion: nil)
        }
        
        saveButton.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { [weak self](btn) in
            self?.saveImage()
        }
        
        pageControl.rac_signalForControlEvents(.ValueChanged).subscribeNext { [weak self](pageControl) in
            
            let indexPath = NSIndexPath(forItem: pageControl.currentPage, inSection: 0)

            self?.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        }
        
    }
    private func preparePageControl(){
    
        //总页
        pageControl.numberOfPages = urls.count
        //当只有一个页面，隐藏
        pageControl.hidesForSinglePage = true
        pageControl.pageIndicatorTintColor = UIColor.whiteColor()
        pageControl.currentPageIndicatorTintColor = UIColor.redColor()
    }
    
//    deinit{
//        print("正常释放内存")
//    }
    
    private func prepareCollectionView(){
    
        //注册可重用标识符
        collectionView.registerClass(PhotoBrowerCell.self, forCellWithReuseIdentifier: HMPhotoBrowserCellID)
        collectionView.dataSource = self
        collectionView.delegate = self
        
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        //滚动方向
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView.pagingEnabled = true
    }
    
    //MARK: - 懒加载控件
    ///集合视图
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
     /// 保存按钮
    private lazy var saveButton:UIButton = UIButton(title: "保存", fontSize: 14)
     /// 关闭按钮
    private lazy var closeButton:UIButton = UIButton(title: "关闭", fontSize: 14)
    /// 分页控件
    private lazy var pageControl:UIPageControl = UIPageControl()
}

// MARK: - UICollectionViewDataSource
extension PhotoBrowserViewController:UICollectionViewDataSource ,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMPhotoBrowserCellID, forIndexPath: indexPath) as! PhotoBrowerCell
        
//        cell.backgroundColor = UIColor.randomColor()
        cell.urls = urls[indexPath.item]
        
        return cell
    }

    
    // 提示： indexPath 是之前一个 cell 的索引
    func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        pageControl.currentPage = collectionView.indexPathsForVisibleItems().last?.item ?? 0
    }
}
















